package com.hjm.common.utils.yh;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ListData {

	private int[][] config;
	private int channelType;
	private LoFunction loFunction = new LoFunction();
	private List<BitMap> bitMapList = new ArrayList<BitMap>();

	public ListData(int[][] config, int channelType) {
		this.config = config;
		this.channelType = channelType;
	}

	public void setlist(int bits, String data) throws Exception {
		BitMap inputBitMap = new BitMap();
		inputBitMap.setBit(bits);
		inputBitMap.setBittype(config[bits][1]);
		inputBitMap.setLen(config[bits][2]);
		inputBitMap.setVariable(config[bits][3]);
		inputBitMap.setDat(changeData(bits, data));
		if (config[bits][3] > 0) {
			inputBitMap.setTruelen(data.getBytes("GBK").length);
		}
		bitMapList.add(inputBitMap);
	}


	public void setlist(int bits, byte[] data) throws Exception {
		BitMap inputBitMap = new BitMap();
		int bit = -1;
		for (int j = 0; j < config.length; j++) {
			if (config[j][0] == bits) {
				bit = j;
				break;
			}
		}
		inputBitMap.setBit(bits);
		inputBitMap.setBittype(config[bit][1]);
		inputBitMap.setLen(config[bit][2]);
		inputBitMap.setVariable(config[bit][3]);
		inputBitMap.setDat(data);
		if (config[bit][3] > 0) {
			if (config[bit][1] == 2) {
				int dataLen = loFunction.bcdTostr(data).length();
				if (dataLen % 2 == 0) {
					dataLen = dataLen - 1;
				}
				inputBitMap.setTruelen(dataLen);
			} else {
				inputBitMap.setTruelen(data.length);
			}
		}
		bitMapList.add(inputBitMap);
	}


	private byte[] changeData(int bits, String data) throws Exception {
		byte[] dat = null;
		switch (config[bits][1]) {
		case 1:
			dat = data.getBytes("GBK");
			break;
		case 2:
			dat = (channelType == 0) ? loFunction.strToBCDBytes(data) : data.getBytes("GBK");
			break;
		case 3:
			dat = loFunction.getAsciiBytes(data);
			break;
		case 4:
			dat = (channelType == 0) ? loFunction.strToBCDBytesRight(data)
					: loFunction.rightZero(data).getBytes("GBK");
			break;
		}
		return dat;
	}


	public List<BitMap> getList() {
		Collections.sort(bitMapList, new Comparator<BitMap>() {
			@Override
			public int compare(BitMap bitMap1, BitMap bitMap2) {
				if (bitMap1.getBit() > bitMap2.getBit()) {
					return 1;
				}
				if (bitMap1.getBit() == bitMap2.getBit()) {
					return 0;
				}
				return -1;
			}
		});
		return bitMapList;
	}

	public void clear() {
		bitMapList.clear();
	}
}